import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:myflutterproject/basematerialwidgetsdemo.dart';

class FilterChipDemo extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => FilterChipState();
}

class ActorFilterEntry {
  final String name;
  final String initials;

  ActorFilterEntry(this.name, this.initials);
}

class FilterChipState extends State<FilterChipDemo> {
  final List<ActorFilterEntry> _cast = <ActorFilterEntry>[
    ActorFilterEntry('标题1', '1'),
    ActorFilterEntry('标题2', '2'),
    ActorFilterEntry('标题3', '3'),
    ActorFilterEntry('标题4', '4'),
  ];
  List<String> _filters = <String>[];

  //Iterable:列表函数
  //yield:应用场景 同步 返回类型Iterable<T>
  Iterable<Widget> get actorWidgets sync* {
    for (ActorFilterEntry actor in _cast) {
      yield Padding(
        padding: EdgeInsets.all(4),
        child: FilterChip(
          avatar: CircleAvatar(
            child: Text(actor.initials),
          ),
          label: Text(actor.name),
          labelStyle: TextStyle(color: Colors.black54),
          selected: _filters.contains(actor.name),
          onSelected: (bool value) {
            //使用setState做到实时刷新
            setState(() {
              if (value) {
                _filters.add(actor.name);
              } else {
                _filters.removeWhere((String name) {
                  return name == actor.name;
                });
              }
            });
          },
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('FilterChip'),
        centerTitle: true,
      ),
      body: Center(
        child: Column(
          children: <Widget>[
            TextWidget('FilterChip自带的比ChoiceChip多一个选中的勾勾的效果'),
            Wrap(
              children: actorWidgets.toList(),
            ),
            Text('Look for: ${_filters.join(', ')}'),
          ],
        ),
      ),
    );
  }
}
